<template>
  <div style="padding: 15px;">
    <div style="margin-bottom: 15px;">
      <Input style="width: 200px;float: left" v-model="searchCourseName" placeholder="请输入课程名称"/>
      <Select style="width: 200px;loat: left"  placeholder="请输入开课机构" v-model="searchOrgId" @on-change="orgIdChange">
        <Option v-for="item in orgIdList" :value="item.id" :key="item.id">{{item.name}}</Option>
      </Select>
      <Select style="width: 200px;loat: left" placeholder="请输入开课教师" v-model="searchTeacherId">
        <Option v-for="item in teacherIdList" :value="item.id" :key="item.id">{{item.loginName}}</Option>
      </Select>
      <Button @click="searchOrg" type="success">搜索</Button>
      <Button @click="add" type="primary" style="float: right;">添加课程</Button>
    </div>
    <Table border ref="selection" :columns="columns" :data="tableData"></Table>
    <page-com :total="total" @page-change="pageChange"></page-com>
    <Modal v-model="addClassesModal" fullscreen :title="modalTitle" @on-ok="submit" @on-cancel="cancel">
      <Form :model="addClassesForm" :label-width="80">
        <Row>
          <Col span="6">
            <FormItem label="课堂名称">
              <Input v-model="addClassesForm.courseName" placeholder="请输入课程名称"/>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="课程价格">
              <Input v-model="addClassesForm.price" placeholder="请输入课程价格"/>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="学生人数">
              <Input v-model="addClassesForm.studentNumber" placeholder="请输入学生人数"/>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="课堂等级">
              <Select v-model="addClassesForm.difficulty">
                <Option value="1">初级</Option>
                <Option value="2">中级</Option>
                <Option value="3">高级</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="6">
            <FormItem label="课堂标签">
              <Select v-model="addClassesForm.labelId" multiple>
                <Option v-for="item in labelIdList" :value="item.id" :key="item.id">{{item.labelName}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="所属机构">
              <Select v-model="addClassesForm.orgId" @on-change="orgIdChange">
                <Option v-for="item in orgIdList" :value="item.id" :key="item.id">{{item.name}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="机构教师">
              <Select v-model="addClassesForm.teacherId">
                <Option v-for="item in teacherIdList" :value="item.id" :key="item.id">{{item.staffName}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem label="课程封面">
              <div class="demo-upload-list" v-for="item in coverUploadList">
                <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="coverRemove(item)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                ref="uploadq"
                :show-upload-list="false"
                :on-success="coverSuccess"
                :format="['jpg','jpeg','png']"
                :before-upload="coverHandleBeforeUpload"
                multiple
                type="drag"
                accept="image/*"
                action="//47.110.52.83:8080/api/picture/upload"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="课程背景图">
              <div class="demo-upload-list" v-for="item in bgUploadList">
                <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="bgRemove(item)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                ref="upload"
                :show-upload-list="false"
                :on-success="bgSuccess"
                :format="['jpg','jpeg','png']"
                :before-upload="bgHandleBeforeUpload"
                multiple
                type="drag"
                accept="image/*"
                action="//47.110.52.83:8080/api/picture/upload"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
              <Modal title="查看大图" v-model="visible">
                <img :src="imgName" v-if="visible" style="width: 100%">
              </Modal>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="4">
            <FormItem label="上传网络图片">
              <div class="demo-upload-list" v-for="item in internetList">
                <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="bgRemove(item)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                ref="upload"
                :show-upload-list="false"
                :on-success="internetSuccess"
                :format="['jpg','jpeg','png']"
                :before-upload="internetBeforeUpload"
                multiple
                type="drag"
                accept="image/*"
                action="//47.110.52.83:8080/api/picture/upload"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </Col>
          <Col span="6"
               v-clipboard:copy="internetPic.join(',')"
               v-clipboard:success="onCopy"
               v-clipboard:error="onError"
          >
            <span v-show="internetPic.length >= 1">{{internetPic.join(',')}}(点我复制)</span>
          </Col>
        </Row>
        <FormItem v-if="flag" label="课程介绍">
          <editor  :dataCon="introduction" :flag="flag"  :catchData="introductionData"/>
        </FormItem>
        <FormItem v-if="flag" label="公告">
          <editor  :dataCon="notice" :flag="flag" :catchData="noticData"/>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="clsdetail" fullscreen title="课程详情">
      <Row type="flex" justify="center">
        <Col span="4">
          <img class="detail-img" :src="details.handcover" alt="">
          <p>课程名称：{{details.courseName}}</p>
          <p>课程价格：{{details.price}}</p>
          <p>所属机构：{{details.orgName}}</p>
          <p>机构教师：{{details.teacherName}}</p>
        </Col>
        <Col span="12">
          <Row>
            <Col span="8">课程章节</Col>
            <Col span="3" offset="13">
              <Button type="primary" @click="addChapter">添加直播</Button>
            </Col>
          </Row>
          <Row class="chapter-layout">
            <Col span="22">
              <div  style="padding: 5px 0;font-size: 16px" v-for="(item, index) in chapterList" :key="index">
                    <span>{{index + 1}}.{{item.livename}}</span>
                    <Button size="small" @click="editorChapter(item)" type="primary">编辑</Button>
                    <Button size="small" @click="chapterdelete(item.id)" type="error">删除</Button>
              </div>
            </Col>
          </Row>
        </Col>
      </Row>
      <Modal :title="chapterTitle" v-model="chapterShow" :mask-closable="false" @on-ok="chapterSubmit" @on-cancel="chaptercancel">
        <Form :label-width="80">
          <FormItem label="直播标题">
            <Input v-model="liveTitle" placeholder="请输入直播标题" />
          </FormItem>
          <FormItem label="开始时间">
            <DatePicker :value="liveDate" @on-change="sectioneTime" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="开课时间"></DatePicker>
          </FormItem>
          <FormItem label="直播名称">
            <Input v-model="liveName" placeholder="请输入直播名称（请使用中文拼音）" />
          </FormItem>
        </Form>
      </Modal>
    </Modal>
  </div>
</template>

<script>
import Editor from '@/components/editor'
import PageCom from '@/components/page'
import {formatDate} from '_com/date'
export default {
  components: {
    Editor,
    PageCom
  },
  data () {
    return {
      liveTitle: '',
      liveName: '',
      liveDate: '',
      liveId: '',
      chapterTitle: '',
      chapterName: '',
      chapterSubtitle: '',
      chapterShow: false,
      addClassesForm: {
        labelId: [],
        orgId: [],
        teacherId: []
      },
      details: {},
      flag: false,
      setUp: false,
      clsdetail: false,
      columns: [
        {
          title: '课程名称',
          key: 'courseName',
          align: 'center'
        },
        {
          title: '课程难度',
          key: 'userName',
          align: 'center',
          render: (h, params) => {
            const row = params.row
            const text = row.difficulty === '1' ? '初级' : row.difficulty === '2' ? '中级' : '高级'
            return h('div', text)
          }
        },
        {
          title: '所属机构',
          key: 'orgName',
          align: 'center'
        },
        {
          title: '所属教师',
          key: 'teacherName',
          align: 'center'
        },
        {
          title: '课程价格（元）',
          key: 'price',
          align: 'center'
        },
        {
          title: '课程标签',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('p', params.row.labelNames.join(','))
            ])
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.details = params.row
                    this.searchChapter(params.row.id)
                    this.clsdetail = true
                  }
                }
              }, '课程详情'),
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editor()
                    let row = params.row
                    this.introduction = row.introduction
                    this.notice = row.notice
                    this.addClassesForm.courseName = row.courseName
                    this.addClassesForm.price = row.price
                    this.addClassesForm.studentNumber = row.studentNumber
                    this.addClassesForm.difficulty = row.difficulty
                    this.addClassesForm.labelId = row.labelIds
                    this.addClassesForm.orgId = row.orgId
                    this.addClassesForm.teacherId = row.teacherId
                    this.coverUploadList = [{url: row.handcover, status: 'finished'}]
                    this.bgUploadList = [{url: row.bgImage, status: 'finished'}]
                    this.bgPic = row.bgImage
                    this.coverPic = row.handcover
                    this.id = row.id
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '你确定要删除吗？',
                      okText: '确定',
                      cancelText: '取消',
                      onOk: () => {
                        this.remove(params.row.id)
                      }
                    })
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      tableData: [],
      size: 10,
      number: 0,
      total: 0,
      searchCourseName: '',
      searchTeacherId: [],
      searchOrgId: [],
      areaModel: '',
      addClassesModal: false,
      modalTitle: '',
      orgBatchAddStudentModal: false,
      content: '',
      imgName: '',
      visible: false,
      bgPic: '',
      bgUploadList: [],
      coverPic: '',
      coverUploadList: [],
      internetPic: [],
      internetList: [],
      labelIdList: [],
      orgIdList: [],
      teacherIdList: [],
      notice: '',
      introduction: '',
      uptoken: {},
      orgId: '',
      chapterList: [],
      chapterId: '',
      sectioneItem: ''
    }
  },
  mounted () {
    this.coursePage()
    this.labelList()
    this.orgList()
    this.teacherList()
  },
  methods: {
    coursePage() {
      this.$get('/api/api/admin/course/page', {
        courseName: this.searchCourseName,
        teacherId: this.searchTeacherId,
        orgId: this.searchOrgId,
        courseType: 1,
        liveType: 1,
        size: this.size,
        number: this.number
      }).then((res) => {
        this.total = res.total
        this.tableData = res.data
      })
    },
    pageChange(data) {
      this.number = data
    },
    labelList() {
      this.$get('/api/api/admin/label/list', {labelCategory: '3'}).then((res) => {
        if (res.code === 0) {
          this.labelIdList = res.data
        }
      })
    },
    orgList() {
      this.$get('/api/api/sys/org/list').then((res) => {
        if (res.code === 0) {
          this.orgIdList = res.data
        }
      })
    },
    teacherList() {
      this.$get('/api/api/org/teacher/list', {orgId: this.orgId}).then((res) => {
        if (res.code === 0) {
          this.teacherIdList = res.data
        }
      })
    },
    orgIdChange(change) {
      this.orgId = change
      this.teacherList()
    },
    title(title) {
      this.modalTitle = title
      this.addClassesModal = true
    },
    add() {
      this.flag = true
      this.title('添加课程')
    },
    editor() {
      this.flag = true
      this.title('编辑课程')
    },
    submit() {
      if (this.modalTitle === '添加课程') {
        this.addOrg()
      } else {
        this.theEditor()
      }
    },
    addOrg() {
      let form = {
        bgImage: this.bgPic,
        courseName: this.addClassesForm.courseName,
        difficulty: this.addClassesForm.difficulty,
        handcover: this.coverPic,
        introduction: this.introduction,
        labelId: this.addClassesForm.labelId,
        notice: this.notice,
        orgId: this.addClassesForm.orgId,
        price: this.addClassesForm.price,
        courseType: 1,
        liveType: 1,
        studentNumber: this.addClassesForm.studentNumber,
        teacherId: this.addClassesForm.teacherId
      }
      this.$post('/api/api/admin/course/add', form).then((res) => {
        if (res.code === 0) {
          this.$Message.success('添加成功')
          this.cancel()
          this.coursePage()
        } else {
          this.$Message.success('添加失败')
        }
      }).catch((rel) => {
        this.$Message.success('添加失败')
      })
    },
    theEditor() {
      let form = {
        bgImage: this.bgPic,
        courseName: this.addClassesForm.courseName,
        difficulty: this.addClassesForm.difficulty,
        handcover: this.coverPic,
        introduction: this.introduction,
        labelId: this.addClassesForm.labelId,
        notice: this.notice,
        orgId: this.addClassesForm.orgId,
        price: this.addClassesForm.price,
        studentNumber: this.addClassesForm.studentNumber,
        teacherId: this.addClassesForm.teacherId,
        id: this.id
      }
      this.$put('/api/api/admin/course/update', form).then((res) => {
        if (res.code === 0) {
          this.$Message.success('编辑成功')
          this.cancel()
          this.coursePage()
        } else {
          this.$Message.success('编辑失败')
        }
      }).catch((rel) => {
        this.$Message.success('编辑失败')
      })
    },
    remove(id) {
      this.$deletes('/api/api/org/course/delete', {id: id}).then((res) => {
        if (res.code === 0) {
          this.$Message.success('删除成功')
          this.coursePage()
        } else {
          this.$Message.success('删除失败')
        }
      }).catch((rel) => {
        this.$Message.success('删除失败')
      })
    },
    searchOrg() {
      this.coursePage()
    },
    cancel() {
      this.flag = false
      this.bgPic = ''
      this.addClassesForm.courseName = ''
      this.addClassesForm.difficulty = ''
      this.coverPic = ''
      this.introduction = ''
      this.addClassesForm.labelId = []
      this.notice = ''
      this.addClassesForm.orgId = []
      this.addClassesForm.price = ''
      this.addClassesForm.studentNumber = ''
      this.addClassesForm.teacherId = []
      this.bgUploadList = []
      this.coverUploadList = []
      this.typeDisabled = false
    },
    introductionData(value) {
      this.introduction = value
    },
    noticData(value) {
      this.notice = value
    },
    handleView(url) {
      this.imgName = url
      this.visible = true
    },
    coverRemove(file) {
      let url = '/api/api/picture/delete'
      let fileUrl = {
        fileUrl: file.url
      }
      this.$deletes(url, fileUrl).then((res) => {
        if (res.message) {
          this.coverPic.splice(this.pic.indexOf(file), 1)
          this.coverUploadList.splice(this.coverUploadList.indexOf(file), 1)
          this.$Message.success('删除成功')
        } else {
          this.$Message.error('删除失败')
        }
      })
    },
    bgRemove(file) {
      let url = '/api/api/picture/delete'
      let fileUrl = {
        fileUrl: file.url
      }
      this.$deletes(url, fileUrl).then((res) => {
        if (res.message) {
          this.bgPic.splice(this.pic.indexOf(file), 1)
          this.bgUploadList.splice(this.bgUploadList.indexOf(file), 1)
          this.$Message.success('删除成功')
        } else {
          this.$Message.error('删除失败')
        }
      })
    },
    coverSuccess(res, file) {
      file.url = file.response.data
      this.$Message.success('上传成功')
      this.coverPic = file.response.data
      this.coverUploadList.push(file)
    },
    bgSuccess(res, file) {
      file.url = file.response.data
      this.$Message.success('上传成功')
      this.bgPic = file.response.data
      this.bgUploadList.push(file)
    },
    bgHandleBeforeUpload() {
      const check = this.bgUploadList.length < 1
      if (!check) {
        this.$Message.error('最多上传1张图片')
      }
      return check
    },
    coverHandleBeforeUpload() {
      const check = this.coverUploadList.length < 1
      if (!check) {
        this.$Message.error('最多上传1张图片')
      }
      return check
    },
    internetBeforeUpload() {
      this.internetPic = []
      this.internetList = []
      const check = this.internetList.length < 1
      if (!check) {
        this.$Message.error('最多上传1张图片')
      }
      return check
    },
    internetSuccess(res, file) {
      file.url = file.response.data
      this.$Message.success('上传成功')
      this.internetPic.push(file.response.data)
      this.internetList.push(file)
    },
    onCopy(e) {
      this.$Message.success('复制成功')
    },
    onError(e) {
      this.$Message.error('复制失败')
    },
    addChapter() {
      this.chapterTitle = '添加直播'
      this.chapterShow = true
    },
    editorChapter(item) {
      this.chapterTitle = '编辑直播'
      this.liveTitle = item.livename
      this.liveName = item.appName
      this.liveDate = formatDate(new Date(item.beginTime), 'yyyy-MM-dd hh:mm')
      this.liveId = item.id
      this.chapterShow = true
    },
    searchChapter(id) {
      this.$get('/api/aliyunVideo/findpage', {sysCourseId: id, size: 10, number: 1}).then((res) => {
        if (res.data.code === 0) {
          this.chapterList = res.data.data
        }
      })
    },
    chapterSubmit() {
      if (this.chapterTitle === '添加直播') {
        this.$post('/api/aliyunVideo/add', {
          livename: this.liveTitle,
          appName: this.liveName,
          beginTime: this.liveDate,
          streamName: this.liveName,
          sysCourseId: this.details.id
        }).then((res) => {
          if (res.code === 0) {
            this.$Message.success('添加成功')
            this.searchChapter(this.details.id)
            this.chaptercancel()
          } else {
            this.$Message.error('添加失败')
          }
        }).catch((res) => {
          this.$Message.error('添加失败')
        })
      } else {
        this.$post('/api/aliyunVideo/update', {
          livename: this.liveTitle,
          appName: this.liveName,
          beginTime: new Date(this.liveDate),
          streamName: this.liveName,
          sysCourseId: this.details.id,
          id: this.liveId
        }).then((res) => {
          if (res.code === 0) {
            this.$Message.success('修改成功')
            this.searchChapter(this.details.id)
            this.chaptercancel()
          } else {
            this.$Message.error('修改失败')
          }
        }).catch((res) => {
          this.$Message.error('修改失败')
        })
      }
    },
    chapterdelete(id) {
      this.$Modal.confirm({
        title: '你确定要删除吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.$post('/api/aliyunVideo/delete', {
            id: id
          }).then((res) => {
            if (res.code === 0) {
              this.$Message.success('删除成功')
              this.searchChapter(this.details.id)
            } else {
              this.$Message.error('删除失败')
            }
          }).catch((res) => {
            this.$Message.error('删除失败')
          })
        }
      })
    },
    chaptercancel() {
      this.liveName = ''
      this.liveTitle = ''
      this.liveDate = ''
    },
    sectioneTime(e) {
      this.liveDate = new Date(e)
    }
  }
}
</script>

<style scoped>
  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .detail-img{
    width: 260px;
    height: 160px;
  }
  .chapter-layout{
    margin-top: 20px;
  }
</style>
